﻿using Rodunu.Business.Interfaces;
using Rodunu.Business.Models.User;

namespace Rodunu.Business.Logic
{
    public class ManageSettings : IManageSettings
    {
        private Settings _settings;
        private readonly Serializer<Settings> _serializer;
        private User _currentUser;

        public ManageSettings()
        {
            _serializer = new Serializer<Settings>();
        }

        #region IManageSettings Members

        public void SaveCurrentSettings()
        {
            int userIndex = 0;
            if (CurrentUser != null)
            {
                foreach (var user in CurrentSettings.Users)
                {
                    if (user.UserName == CurrentUser.UserName)
                    {
                        break;
                    }
                    userIndex++;
                }

                CurrentSettings.Users[userIndex] = _currentUser;

                Properties.Settings.Default.CurrentSettings = _serializer.SerializeToString(_settings);
                Properties.Settings.Default.Save();
            }
        }

        public void DeleteCurrentSettings()
        {
            Properties.Settings.Default.CurrentSettings = null;
            Properties.Settings.Default.Save();
        }

        public Settings CurrentSettings
        {
            get
            {
                if (_settings == null)
                {
                    if (Properties.Settings.Default.CurrentSettings.Length > 0)
                        _settings =
                            _serializer.DeserializeFromString(Properties.Settings.Default.CurrentSettings) ?? new Settings();
                    else
                        _settings = new Settings();
                }
                return _settings;
            }
        }

        public User CurrentUser
        {
            get
            {
                return _currentUser;

            }
            set
            {
                _currentUser = value;
                
            }
        }

        #endregion
    }
}
